<?php

	// delete file if exist
	if(file_exists("category.txt")){
		
		unlink("category.txt");
	}
	
	if(file_exists("product.txt")){
		
		unlink("product.txt");
	}
	
	if(file_exists("content.txt")){
		
		unlink("content.txt");
	}
	
	if(file_exists("products.txt")){
		
		unlink("products.txt");
	}
?>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">

// category main link
var CATE_ARR = ['http://www.watchcartoononline.com/dubbed-anime-list',
                'http://www.watchcartoononline.com/cartoon-list',
                'http://www.watchcartoononline.com/subbed-anime-list',
                'http://www.watchcartoononline.com/movie-list'];


var indexOfMainCate = 0;

var indexOfCate = 0;
var listCate;

var indexOfProd = 0;
var listProd;

$(document).ready(function() {
	
	$("body").append("Get category " + CATE_ARR[indexOfMainCate] + "<br/>");

	getCategory();
});


function getCategory() {

	$.ajax({
		   url:"getCate.php",
		   type:"POST",
		   data:{url:CATE_ARR[indexOfMainCate]},
		   success: function (data){
			   
			  $("body").append(data);
			  indexOfMainCate++;
			  
			  if(indexOfMainCate < CATE_ARR.length) {

				  $("body").append("Get category " + CATE_ARR[indexOfMainCate] + "<br/>");
				  getCategory();
			  } else {

				  listCate = $(".hdCate");
				  
				  getProd();
			  }
		   }
	});
}

		
function getProd() {
		
	var cateLink = listCate[indexOfCate];
	$("body").append("Get prod of " + $(cateLink).val() + "<br/>");

	$.ajax({
		url:"getProd.php",
		type:"POST",
		data:{url:$(cateLink).val()},
		success: function (data){

			$("body").append(data);
						  
			indexOfCate++;
		
			if(indexOfCate < listCate.length) {
		
				getProd();
				
			} else {

				listProd = $(".hdProd");
				
				getContent();
			}
		}
	});
}

function getContent(){
	
	var prodLink = listProd[indexOfProd];

	$.ajax({
		url:"getContent.php",
		type:"POST",
		data:{ url : $(prodLink).val() },
		success: function (data){
						  
			indexOfProd++;

			if(indexOfProd < listProd.length) {

				getContent();
			} else {

				
				
				$("body").append("Get content completed!<br/>");

				mergeFile();

				$("body").append("Merge data completed!<br/>");
			}
		}
					
	});
}

function mergeFile(){

	$.ajax({

		url:'merge.php',
		success : function(data) {

			alert("Get data complete!");
		}
	});
}

</script>
</head>
<body>

</body>
</html>
